package com.ruoyi.demo.controller.app;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.demo.domain.AuctionGoods;
import com.ruoyi.demo.domain.dto.AuctionFavoriteWithGoodsDTO;
import com.ruoyi.demo.domain.dto.AuctionGoodsDetailDTO;
import com.ruoyi.demo.service.IAuctionGoodsService;
import com.ruoyi.demo.service.IAuctionRecordService;
import com.ruoyi.demo.service.IAuctionFavoriteService;
import com.ruoyi.demo.utils.RequestUtils;
import com.ruoyi.demo.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "小程序-商品信息")
@RestController
@RequestMapping("/app/goods")
public class AppAuctionGoodsController extends BaseController {
    @Autowired
    private IAuctionGoodsService auctionGoodsService;
    
    @Autowired
    private IAuctionRecordService auctionRecordService;
    
    @Autowired
    private IAuctionFavoriteService auctionFavoriteService;

    /**
     * 获取当前用户ID（从token中获取）
     * 
     * @return 用户ID，如果未登录则返回null
     */
    private Long getCurrentUserId() {
        // 从请求头获取token
        String token = RequestUtils.getToken();
        if (token != null && !token.isEmpty()) {
            // 从token中解析用户ID
            return TokenUtils.getUserIdFromToken(token);
        }
        return null;
    }

    @ApiOperation("查询商品信息列表")
    @GetMapping("/list")
    public TableDataInfo list(
            @ApiParam(value = "商品信息查询对象") AuctionGoods auctionGoods,
            @ApiParam(value = "是否包含已结束商品", defaultValue = "true") @RequestParam(defaultValue = "true") Boolean includeEnded
    ) {
        auctionGoods.setIncludeEnded(includeEnded);
        startPage();
        List<AuctionGoods> list = auctionGoodsService.selectAuctionGoodsList(auctionGoods);
        
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        
        // 如果用户已登录，为商品添加收藏状态
        if (userId != null && !list.isEmpty()) {
            // 为每个商品添加收藏状态和收藏ID
            list.forEach(goods -> {
                Map<String, Object> favoriteInfo = auctionFavoriteService.getFavoriteInfo(userId, goods.getGoodsId());
                boolean isFavorite = (boolean) favoriteInfo.get("isFavorite");
                goods.getParams().put("favoriteStatus", isFavorite);
                
                // 如果已收藏，添加收藏ID
                if (isFavorite) {
                    goods.getParams().put("favoriteId", favoriteInfo.get("favoriteId"));
                }
            });
        }
        
        return getDataTable(list);
    }

    @ApiOperation("获取商品信息详细信息")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@ApiParam(value = "商品ID", required = true) @PathVariable("goodsId") Long goodsId) {
        AuctionGoodsDetailDTO goodsDetail = auctionGoodsService.selectAuctionGoodsDetailByGoodsId(goodsId);
        
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        
        // 如果用户已登录，添加收藏状态
        if (userId != null && goodsDetail != null) {
            Map<String, Object> favoriteInfo = auctionFavoriteService.getFavoriteInfo(userId, goodsId);
            boolean isFavorite = (boolean) favoriteInfo.get("isFavorite");
            goodsDetail.setFavoriteStatus(isFavorite);
            
            // 如果已收藏，添加收藏ID
            if (isFavorite) {
                goodsDetail.setFavoriteId((Long) favoriteInfo.get("favoriteId"));
            }
        } else if (goodsDetail != null) {
            // 用户未登录，默认未收藏
            goodsDetail.setFavoriteStatus(false);
        }
        
        return success(goodsDetail);
    }

    @ApiOperation("新增商品信息")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AuctionGoods auctionGoods) {
        return toAjax(auctionGoodsService.insertAuctionGoods(auctionGoods));
    }

    @ApiOperation("修改商品信息")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AuctionGoods auctionGoods) {
        return toAjax(auctionGoodsService.updateAuctionGoods(auctionGoods));
    }

    @ApiOperation("删除商品信息")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsIds}")
    public AjaxResult remove(@PathVariable Long[] goodsIds) {
        return toAjax(auctionGoodsService.deleteAuctionGoodsByGoodsIds(goodsIds));
    }

    @ApiOperation("获取商品出价历史列表")
    @GetMapping("/{goodsId}/bid-history")
    public AjaxResult getBidHistory(@ApiParam(value = "商品ID", required = true) @PathVariable("goodsId") Long goodsId) {
        return success(auctionRecordService.selectAuctionRecordListByGoodsId(goodsId));
    }
} 